package com.whuan.user.controller;

import com.whuan.user.constant.CookieConstant;
import com.whuan.user.constant.RedisConstant;
import com.whuan.user.dataObject.User;
import com.whuan.user.dto.UserDTO;
import com.whuan.user.enums.ResultEnum;
import com.whuan.user.exception.IbestException;
import com.whuan.user.form.UserForm;
import com.whuan.user.service.UserService;
import com.whuan.user.util.CookieUtil;
import com.whuan.user.util.UserDTOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/index")
    public ModelAndView index(Map<String,Object> map){
        return new ModelAndView("user/index",map);
    }

    @GetMapping("/onePage")
    public String onePage(Map<String,Object> map){
        return "onePage";
    }

    /*@PostMapping("/login")
    public ModelAndView login(@Valid UserForm userForm, BindingResult bindingResult, HttpServletResponse response, Map<String,Object> map){
        //判断表单验证是否成功
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", userForm);
            throw new IbestException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        //1、本地验证用户名、密码是否正确
        User user = userService.findByUserForm(userForm);
        log.info("user={}",user);
        if(user==null){
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/ibest/userController/index");
            return new ModelAndView("common/error", map);
        }
        map.put("userInfo",user);
        //2、设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,user.getUserId()),token,expire, TimeUnit.SECONDS);

        //3、token 设置cookie
        CookieUtil.set(response, String.format(CookieConstant.TOKEN,user.getUserId()),token,expire);

        return new ModelAndView("user/main",map);
    }
        @RequestMapping("/logout")
        public ModelAndView logout(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @RequestParam("userId") String userId,
                                   Map<String,Object> map){
            //从cookie中查登录信息
            String cookieToken = String.format(CookieConstant.TOKEN,userId);
            Cookie cookie = CookieUtil.get(request,cookieToken);
            if(cookie!=null){
                //2、清除redis
                redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,userId));
                //3、清除cookie
                CookieUtil.set(response,cookieToken,null,0);
            }

            map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMessage());
            map.put("url","/ibest/userController/index");
            return new ModelAndView("common/success",map);
        }

    *//**
     * create by: whaun
     * create date:  2019/5/20 time:6:57
     * description: 用户进入注册页面
     *//*
    @GetMapping("/register")
    public ModelAndView register(Map<String,Object> map){
        log.info("进入注册页面");
        return new ModelAndView("user/register",map);
    }

    *//**
     * create by: whaun
     * create date:  2019/5/20 time:6:57
     * description:用户发起注册
     *//*
    @RequestMapping("/registerUser")
    public ModelAndView registerUser(@Valid UserForm userForm, BindingResult bindingResult, Map<String,Object> map){
        log.info("用户开始注册");
        //1、判断表单验证是否成功
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", userForm);
            throw new IbestException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        //2、获取UserDTO
        UserDTO userDTO = UserDTOUtil.getUserDTO(userForm);

        //3、保存UserDto
        userService.save(userDTO);

        return new ModelAndView("user/index",map);
    }*/


}
